
package com.mengmeizi.services;

import com.mengmeizi.db.DBHelper;
import com.mengmeizi.db.WallpaperDBBean;

import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class ChangeWallpaperService extends Service {

    private static int index = 0;

    private DBHelper helper;

    // private List<WallpaperDBBean> paperBeans;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        helper = new DBHelper(this, WallpaperDBBean.TABLE);
        // if (paperBeans == null) {
        // paperBeans = new ArrayList<WallpaperDBBean>();
        // }
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);

        // 读取数据库数据
        helper.openReadableDatabase();
        Cursor cursor = helper.getDatas(WallpaperDBBean.sql$selectAll());
        int count = cursor.getCount();
        cursor.close();
        // WallpaperDBBean tmpBean = null;
        // while (cursor.moveToNext()) {
        // tmpBean = WallpaperDBBean.conver2Datas(cursor);
        // paperBeans.add(tmpBean);
        // }
        // helper.close();

        // 获得需要展示的图片索引
        if (index >= (count - 1)) {
            index = 0;
        } else {
            index++;
        }
        cursor = helper.getDatas(WallpaperDBBean.sql$selectObject(index));
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            String imageFileName = cursor.getString(cursor.getColumnIndex(WallpaperDBBean.LOCALPATH));
            cursor.close();
            helper.close();
            InputStream is = null;
            try {
                // 将文件读成流
                is = new BufferedInputStream(new FileInputStream(new File(imageFileName)));
                // 通过流设置壁纸
                setWallpaper(is);
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                stopSelf();
            }
        }
    }
}
